<template>
  <div class="product-container">
    <div class="header">
      <h2>商品管理</h2>
      <el-button 
        v-if="userStore.canManageProducts" 
        type="primary" 
        @click="handleAdd"
      >添加商品</el-button>
    </div>

    <!-- 搜索表单 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="商品名称">
        <el-input v-model="searchForm.name" placeholder="请输入商品名称" clearable />
      </el-form-item>
      <el-form-item label="分类">
        <el-select v-model="searchForm.categoryId" placeholder="请选择分类" clearable>
          <el-option
            v-for="item in categories"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 商品列表 -->
    <el-table :data="products" border style="width: 100%">
      <el-table-column prop="productId" label="ID" width="80" sortable />
      <el-table-column prop="productName" label="商品名称" />
      <el-table-column prop="categoryName" label="分类" width="120">
        <template #default="{ row }">
          {{ getCategoryName(row.categoryId) }}
        </template>
      </el-table-column>
      <el-table-column prop="productPrice" label="价格" width="120">
        <template #default="{ row }">
          ¥{{ row.productPrice?.toFixed(2) || '0.00' }}
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存" width="100" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button 
            v-if="userStore.canManageProducts"
            type="primary" 
            link 
            @click="handleEdit(row)"
          >编辑</el-button>
          <el-button 
            v-if="userStore.canManageProducts"
            type="danger" 
            link 
            @click="handleDelete(row)"
          >删除</el-button>
          <el-button 
            v-if="userStore.canBuyProducts"
            type="success" 
            link 
            @click="handleBuy(row)"
          >购买</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑商品对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="商品名称" prop="product_name">
          <el-input v-model="form.product_name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品分类" prop="category_id">
          <el-select v-model="form.category_id" placeholder="请选择分类">
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品价格" prop="product_price">
          <el-input-number
            v-model="form.product_price"
            :precision="2"
            :step="0.1"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="商品库存" prop="stock">
          <el-input-number
            v-model="form.stock"
            :min="0"
            :precision="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入商品描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 购买表单对话框 -->
    <el-dialog
      title="购买商品"
      v-model="purchaseDialogVisible"
      width="500px"
    >
      <el-form
        ref="purchaseFormRef"
        :model="purchaseForm"
        :rules="purchaseRules"
        label-width="100px"
      >
        <el-form-item label="商品名称">
          <span>{{ selectedProduct?.productName }}</span>
        </el-form-item>
        <el-form-item label="单价">
          <span>¥{{ selectedProduct?.productPrice?.toFixed(2) }}</span>
        </el-form-item>
        <el-form-item label="库存">
          <span>{{ selectedProduct?.stock }}</span>
        </el-form-item>
        <el-form-item label="购买数量" prop="quantity">
          <el-input-number
            v-model="purchaseForm.quantity"
            :min="1"
            :max="selectedProduct?.stock"
            :precision="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="总金额">
          <span class="text-red">¥{{ totalAmount }}</span>
        </el-form-item>
        <el-form-item label="收货人" prop="shippingName">
          <el-input v-model="purchaseForm.shippingName" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="shippingPhone">
          <el-input v-model="purchaseForm.shippingPhone" placeholder="请输入收货人电话" />
        </el-form-item>
        <el-form-item label="收货地址" prop="shippingAddress">
          <el-input
            v-model="purchaseForm.shippingAddress"
            type="textarea"
            :rows="3"
            placeholder="请输入详细收货地址"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="purchaseDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePurchaseSubmit">确认购买</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useProductStore } from '@/store/modules/product'
import { useCategoryStore } from '@/store/modules/category'
import { useOrderStore } from '@/store/modules/order'
import { useUserStore } from '@/store/modules/user'
import { formatDate } from '@/utils/format'
import { purchaseProduct } from '@/api/product'
import { useRouter } from 'vue-router'

// 初始化 store 和 router
const productStore = useProductStore()
const categoryStore = useCategoryStore()
const orderStore = useOrderStore()
const userStore = useUserStore()
const router = useRouter()

// 数据列表
const products = ref([])
const categories = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)

// 表单数据
const form = ref({
  product_id: undefined,
  product_name: '',
  category_id: undefined,
  product_price: 0,
  stock: 0,
  description: ''
})

// 表单验证规则
const rules = {
  product_name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  category_id: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  product_price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { type: 'number', message: '价格必须为数字', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value < 0) {
          callback(new Error('价格不能小于0'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  stock: [
    { required: true, message: '请输入商品库存', trigger: 'blur' },
    { type: 'number', message: '库存必须为数字', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value < 0) {
          callback(new Error('库存不能小于0'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取商品列表
const fetchProducts = async () => {
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchForm.name,
      categoryId: searchForm.categoryId
    }
    console.log('获取商品列表，参数:', params)
    await productStore.getProducts(params)
    // 对商品列表进行排序
    products.value = [...productStore.products].sort((a, b) => {
      const idA = parseInt(a.productId) || 0
      const idB = parseInt(b.productId) || 0
      return idA - idB
    })
    total.value = productStore.total
  } catch (error) {
    console.error('获取商品列表失败:', error)
  }
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    await categoryStore.getCategories()
    categories.value = categoryStore.categories.map(category => ({
      id: category.categoryId || category.id,
      name: category.categoryName || category.name,
      ...category
    }))
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}

// 获取分类名称
const getCategoryName = (categoryId) => {
  const category = categories.value.find(item => 
    item.id === categoryId || item.categoryId === categoryId
  )
  return category ? (category.name || category.categoryName) : '-'
}

// 搜索表单
const searchForm = reactive({
  name: '',
  categoryId: ''
})

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchProducts()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.categoryId = ''
  currentPage.value = 1
  fetchProducts()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchProducts()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchProducts()
}

// 添加商品
const handleAdd = () => {
  // 检查权限
  if (!userStore.canManageProducts) {
    ElMessage.warning('您没有权限添加商品')
    return
  }
  
  dialogTitle.value = '添加商品'
  form.value = {
    product_id: undefined,
    product_name: '',
    category_id: undefined,
    product_price: 0,
    stock: 0,
    description: ''
  }
  dialogVisible.value = true
}

// 编辑商品
const handleEdit = (row) => {
  // 检查权限
  if (!userStore.canManageProducts) {
    ElMessage.warning('您没有权限编辑商品')
    return
  }
  
  dialogTitle.value = '编辑商品'
  form.value = {
    product_id: row.productId,
    product_name: row.productName,
    category_id: row.categoryId,
    product_price: row.productPrice,
    stock: row.stock,
    description: row.description
  }
  dialogVisible.value = true
}

// 删除商品
const handleDelete = async (row) => {
  // 检查权限
  if (!userStore.canManageProducts) {
    ElMessage.warning('您没有权限删除商品')
    return
  }
  
  try {
    await ElMessageBox.confirm('确认删除该商品吗？', '提示', {
      type: 'warning'
    })
    await productStore.deleteProduct(row.productId)
    fetchProducts()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除商品失败:', error)
    }
  }
}

// 购买相关
const purchaseDialogVisible = ref(false)
const purchaseForm = ref({
  quantity: 1,
  shippingAddress: '',
  shippingName: '',
  shippingPhone: ''
})
const selectedProduct = ref(null)

const purchaseRules = {
  quantity: [
    { required: true, message: '请输入购买数量', trigger: 'blur' },
    { type: 'number', message: '数量必须为数字', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (!selectedProduct.value) {
          callback(new Error('商品信息不存在'))
          return
        }
        if (value <= 0) {
          callback(new Error('购买数量必须大于0'))
        } else if (value > selectedProduct.value.stock) {
          callback(new Error('购买数量不能超过库存数量'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  shippingAddress: [
    { required: true, message: '请输入收货地址', trigger: 'blur' },
    { min: 5, max: 200, message: '地址长度在 5 到 200 个字符', trigger: 'blur' }
  ],
  shippingName: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' },
    { min: 2, max: 50, message: '姓名长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  shippingPhone: [
    { required: true, message: '请输入收货人电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

const purchaseFormRef = ref(null)

// 打开购买对话框
const handleBuy = (row) => {
  // 检查权限
  if (!userStore.canBuyProducts) {
    ElMessage.warning('您没有权限购买商品')
    return
  }
  
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  selectedProduct.value = row
  purchaseForm.value = {
    quantity: 1,
    shippingAddress: '',
    shippingName: '',
    shippingPhone: ''
  }
  purchaseDialogVisible.value = true
}

// 提交购买
const handlePurchaseSubmit = async () => {
  if (!purchaseFormRef.value) return
  
  try {
    await purchaseFormRef.value.validate()
    
    const res = await purchaseProduct(selectedProduct.value.productId, purchaseForm.value)
    
    if (res.code === 200) {
      ElMessage.success('购买成功，请前往订单列表查看')
      purchaseDialogVisible.value = false
      // 刷新商品列表（更新库存）
      fetchProducts()
      // 跳转到订单列表页
      router.push('/orders')
    } else {
      throw new Error(res.message || '购买失败')
    }
  } catch (error) {
    console.error('购买失败:', error)
    ElMessage.error(error.message || '购买失败')
  }
}

// 计算总金额
const totalAmount = computed(() => {
  if (!selectedProduct.value) return 0
  return (selectedProduct.value.productPrice * purchaseForm.value.quantity).toFixed(2)
})

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (form.value.product_id) {
      // 更新商品
      await productStore.updateProduct({
        id: form.value.product_id,
        productName: form.value.product_name,
        categoryId: form.value.category_id,
        productPrice: form.value.product_price,
        stock: form.value.stock,
        description: form.value.description
      })
    } else {
      // 创建商品
      await productStore.createProduct({
        productName: form.value.product_name,
        categoryId: form.value.category_id,
        productPrice: form.value.product_price,
        stock: form.value.stock,
        description: form.value.description
      })
    }
    
    dialogVisible.value = false
    fetchProducts()
  } catch (error) {
    console.error('提交表单失败:', error)
  }
}

// 初始化数据
onMounted(async () => {
  await Promise.all([fetchProducts(), fetchCategories()])
})
</script>

<style scoped>
.product-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.text-red {
  color: #f56c6c;
  font-weight: bold;
  font-size: 18px;
}
</style> 